﻿using Cache;
using Domain.Entity;
using DtoFw;
using DtoFw.Base;
using DtoFw.Query;
using DtoFw.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SceneEvidenceAPI.Models;
using Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SceneEvidenceAPI.Controllers
{
    /// <summary>
    /// 系统
    /// </summary>
    [Route("api/common")]
    public class MainCommonController : BaseController
    {
        private readonly MainHomeService rep_home;
        private readonly DbBakService dbBak;
        public MainCommonController(MainHomeService home, DbBakService _dbBak)
        {
            rep_home = home;
            dbBak = _dbBak;
        }
        /// <summary>
        /// 获取系统操作日志
        /// </summary>
        /// <returns></returns>
        [HttpGet("logs")]
        public BaseGenericResult<Pager<LogResult>> GetLogs([FromQuery] LogQuery query)
        {
            return rep_home.GetLogs(query);
        }
        /// <summary>
        /// 预警保存
        /// </summary>
        /// <returns></returns>
        [HttpPost("post/waraing")]
        public BaseResult SaveWarningConfig([FromBody] ConfigRequestDto dto)
        {
            return rep_home.SaveWarningConfig(dto);
        }
        /// <summary>
        ///  检查是否激活
        /// </summary>
        /// <returns></returns>
        [HttpGet("checkReg")]
        [AllowAnonymous]
        public BaseResult CheckReg()
        {
            var uqkey = Util.Tools.GetUQCode();
            var error = "";
            if (string.IsNullOrEmpty(uqkey))
            {
                uqkey = Guid.NewGuid().ToString("n");
                error = Util.Tools.WriteSetting("uqkey", uqkey);
                if (!string.IsNullOrEmpty(error))
                {
                    //写入注册表失败
                    uqkey = "";
                }
            }
            var ret = new BaseGenericResult<object>()
            {
                Code = DtoFw.Enum.EnumReturnCode.Success,
                Success = true,
                Msg = error,
                Data = new
                {
                    uqkey,
                    isReg = Util.Tools.CheckReg(uqkey)
                }
            };
            return ret;
        }
        /// <summary>
        ///  检查是否激活
        /// </summary>
        /// <returns></returns>
        [HttpPost("submitReg")]
        [AllowAnonymous]
        public BaseResult SubmitReg(string rval)
        {
            var ret = new BaseGenericResult<object>()
            {
                Code = DtoFw.Enum.EnumReturnCode.Success,
                Success = true
            };
            var uqkey = Util.Tools.GetUQCode();
            if (Util.Tools.CheckEq(uqkey, rval))
            {
                Util.Tools.WriteSetting("uqkey_rval", rval);
            }
            else
            {
                ret.Success = false;
                ret.Msg = "激活码无效";
            }

            return ret;
        }

        #region 系统配置

        /// <summary>
        /// 保存系统配置
        /// </summary>
        /// <returns></returns>
        [HttpPost("post/systemconfig")]
        public BaseResult SaveSystemConfig([FromBody] SystemConfigDto dto)
        {
            return rep_home.SaveSystemConfig(dto);
        }
        /// <summary>
        /// 保存系统配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("query/systemconfig")]
        [AllowAnonymous]
        public BaseResult SaveSystemConfig()
        {
            return rep_home.QuerySystemConfigDto();
        }

        #endregion

        #region 硬件配置
        /// <summary>
        /// 保存系统配置
        /// </summary>
        /// <returns></returns>
        [HttpPost("post/Hardware")]
        public BaseResult SaveHardwareConfig([FromBody] HandwareConfigDto dto)
        {
            return rep_home.SaveHardwareConfig(dto);
        }
        /// <summary>
        /// 保存系统配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("query/Hardware")]
        [AllowAnonymous]
        public BaseResult SaveHardwareConfig()
        {
            return rep_home.QueryHardwareDto();
        }
        #endregion 硬件配置

        #region 流程配置
        /// <summary>
        /// 保存系统配置
        /// </summary>
        /// <returns></returns>
        [HttpPost("post/FlowConfig")]
        public BaseResult SaveFlowConfig([FromBody] HandwareConfigDto dto)
        {
            return rep_home.SaveFlowConfig(dto);
        }
        /// <summary>
        /// 保存系统配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("query/FlowConfig")]
        [AllowAnonymous]
        public BaseResult QueryFlowConfig()
        {
            return rep_home.QueryFlowConfig();
        }
        #endregion 流程配置

        #region 数据库备份
        /// <summary>
        /// 保存备份配置
        /// </summary>
        /// <returns></returns>
        [HttpPost("post/BakConfig")]
        public BaseResult BakConfig([FromBody] HandwareConfigDto dto)
        {
            return rep_home.SaveBakConfig(dto);
        }
        /// <summary>
        /// 保存备份配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("query/BakConfig")]
        [AllowAnonymous]
        public BaseResult QueryBakConfig()
        {
            return rep_home.QueryBakConfig();
        }
        /// <summary>
        /// 获取系统操作日志
        /// </summary>
        /// <returns></returns>
        [HttpGet("queryDbBakList")]
        public BaseGenericResult<Pager<DbbakEntity>> QueryDbBakList([FromQuery] LogQuery query)
        {
            return dbBak.QueryBakList(query);
        }
        /// <summary>
        /// 获取系统操作日志
        /// </summary>
        /// <returns></returns>
        [HttpPost("deleteDbBak")]
        public BaseGenericResult<object> DeleteDbBak([FromBody] BaseQuery query)
        {
            return BaseGenericResult<object>.Succeed(dbBak.Delete(query));
        }

        #endregion 数据库备份
        /// <summary>
        /// 预警保存
        /// </summary>
        /// <returns></returns>
        [HttpGet("get/waraing/{classCode}/{categoryCode}")]
        public BaseGenericResult<ConfigRequestDto> GetWarningConfig(string classCode, string categoryCode)
        {
            return rep_home.GetWarningConfig(classCode, categoryCode);
        }
        /// <summary>
        /// 常规配置保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("post/config/setting")]
        public BaseResult SaveConfigSetting([FromBody] ConfigSettingDto dto)
        {
            return rep_home.SaveConfigSetting(dto);
        }
        /// <summary>
        /// 获取关联照片
        /// </summary>
        /// <param name="relevanceId"></param>
        /// <returns></returns>
        [HttpGet("imgs/{relevance}/{type}")]
        public BaseGenericResult<List<BaseImgRespDto>> GetImgs(string relevance,
            int type = 0)
        {
            return rep_home.GetImgs(relevance, type);
        }

        /// <summary>
        /// 入库前检查照片是否录入
        /// </summary>
        /// <param name="wzs"></param>
        /// <returns></returns>
        [HttpPost("imgs/checkImgs")]
        public BaseGenericResult<bool> CheckImgs(List<BaseImgRespDto> wzs)
        {
            return rep_home.CheckImgs(wzs);
        }

            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="relevanceId"></param>
            /// <returns></returns>
            [HttpDelete("imgs/delete")]
        public BaseResult DeleteImg([FromBody] DeleteSingleDto deleteDto)
        {
            return rep_home.DeleteImg(deleteDto);
        }
        /// <summary>
        /// 上传附件图片
        /// </summary>
        /// <returns>文件相对路径</returns>
        [HttpPost("upload/img")]
        [DisableRequestSizeLimit]
        public BaseGenericResult<string> UploadImgOne(IFormFile f)
        {
            string ossurl = string.Empty;
            var file = Request.Form.Files.First();
            if (file.Length < 1)
                return BaseGenericResult<string>.Failure(ossurl, "参数错误");
            FileInfo fileInfo = new FileInfo(file.FileName);
            string ty = Request.Form.First(x => x.Key == "ty").Value.ToString();
            string id = Request.Form.First(x => x.Key == "id").Value.ToString();
            string no = "";
            if (Request.Form.Keys.Contains("no"))
            {
                no = Request.Form.First(x => x.Key == "no").Value.ToString();
                if (!string.IsNullOrWhiteSpace(no))
                    id = "0";
            }
            using (var stream = file.OpenReadStream())
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin);
                TokenData tokenData = TokenHelper.GetTokenInfo<TokenData>(User);
                return rep_home.UploadImg(tokenData.UserId, ty, id, no, fileInfo, bytes);
            }
        }

        /// <summary>
        /// 上传base64照片
        /// </summary>
        /// <param name="imgs"></param>
        /// <returns></returns>
        [HttpPost("upload/base64img")]
        [AllowAnonymous]
        [DisableRequestSizeLimit]
        public BaseResult UploadImgBase64([FromBody] ImageBase64ImgReqDto reqDto)
        {
            TokenData tokenData = TokenHelper.GetTokenInfo<TokenData>(User);
            if ((reqDto.RelevanceId <= 0 && string.IsNullOrWhiteSpace(reqDto.RelevanceNo)) || reqDto.base64Imgs == null || reqDto.base64Imgs.Count < 1)
                return BaseResult.Failure("传入参数为空");
            List<Byte[]> list = reqDto.base64Imgs.Select(x => { return Convert.FromBase64String(x); })?.ToList();
            return rep_home.UploadBase64Imgs(tokenData.UserId, reqDto.Type, reqDto.RelevanceId, reqDto.RelevanceNo, list);
        }

        /// <summary>
        /// WebScoket测试
        /// </summary>
        /// <param name="relevanceId"></param>
        /// <returns></returns>
        [HttpPost("webscoket/send")]
        [AllowAnonymous]
        public BaseResult WebScoketSend([FromBody] WebScoketReqDto reqDto)
        {
            return rep_home.WebScoketSend(reqDto);
        }
        [HttpGet("test")]
        [AllowAnonymous]
        public ActionResult Test()
        {
            Util.EngineContext.Resolve<DbBakService>().RunDbBakCmd();
            return Content("ok");
        }

        #region 档案附件上传

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns>文件相对路径</returns>
        [HttpPost("upload/caseattachfile")]
        [DisableRequestSizeLimit]
        public BaseGenericResult<string> UploadCaseAttachFile(IFormFile f)
        {
            string ossurl = string.Empty;
            var file = Request.Form.Files.First();
            if (file.Length < 1)
                return BaseGenericResult<string>.Failure(ossurl, "参数错误");
            FileInfo fileInfo = new FileInfo(file.FileName);
            //案件id
            string caseid = Request.Form["caseid"];
            //档案id
            string evidenceId = Request.Form["evidenceId"];
            if (string.IsNullOrEmpty(caseid))
            {
                return BaseGenericResult<string>.Failure(ossurl, "案件id不能为空！");
            }
            if (string.IsNullOrEmpty(evidenceId))
                evidenceId = "0";

            using (var stream = file.OpenReadStream())
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin);
                TokenData tokenData = TokenHelper.GetTokenInfo<TokenData>(User);
                return rep_home.UploadCaseAttachFile(tokenData, caseid, evidenceId, fileInfo, bytes);
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns>文件相对路径</returns>
        [HttpGet("upload/camerAttr/{caseid}/{evidenceId}/{url}")]
        [AllowAnonymous]
        public BaseGenericResult<string> UploadCaseAttachFile(string caseid, string evidenceId, string url)
        {

            url= Uri.UnescapeDataString(url);
            string ossurl = string.Empty;
            ////案件id
            //string caseid = Request.Form["caseid"];
            ////档案id
            //string evidenceId = Request.Form["evidenceId"];
            //string url= Request.Form["url"];
            if (string.IsNullOrEmpty(caseid))
            {
                return BaseGenericResult<string>.Failure(ossurl, "案件id不能为空！");
            }
            if (string.IsNullOrEmpty(evidenceId))
                evidenceId = "0";

            TokenData tokenData = TokenHelper.GetTokenInfo<TokenData>(User);
            return rep_home.UploadCaseAttachFile(tokenData, caseid, evidenceId, url);

        }

        #endregion 档案附件上传
    }
}
